/*
 * Copyright (C) 2017 zhouyou(478319399@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zhouyou.http.demo.slice;

import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.DownloadProgressCallBack;
import com.zhouyou.http.demo.ResourceTable;
import com.zhouyou.http.model.utils.FileUtils;
import com.zhouyou.http.model.utils.ToastUtils;
import com.zhouyou.http.demo.view.HorizontalProgressDialog;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.utils.HttpLog;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;

import static com.zhouyou.http.demo.constant.AppConstant.*;

public class DownloadAbilitySlice extends AbilitySlice {
    private HorizontalProgressDialog dialog;

    public String getResults() {
        return results;
    }

    private  String  results="";

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_download);

        dialog = new HorizontalProgressDialog(this);

        dialog.setMessage("正在下载...");
        // 设置提示的title的图标，默认是没有的，如果没有设置title的话只设置Icon是不会显示图标的
        dialog.setTitle("下载文件");
        dialog.setMax(100);
        findComponentById(ResourceTable.Id_btn_down_loade_file1).setClickedListener(component -> {
            onDownloadFile1();
        });
        findComponentById(ResourceTable.Id_btn_down_load_file2).setClickedListener(component -> {

            onDownloadFile2();
        });


    }


    public void onDownloadFile1() {//下载回调是在异步里处理的
        dialog = new HorizontalProgressDialog(this);
        EasyHttp.downLoad(new StringBuffer(SCHEMA).append(HIAPK).append(HIAPK_WEB).toString())
                .savePath(FileUtils.getDistDir(this) + "test/")//默认在：/storage/emulated/0/OS/data/包名/files/1494647767055
                .saveName("custom_name")//默认名字是时间戳生成的
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void update(long bytesRead, long contentLength, boolean done) {
                        int progress = (int) (bytesRead * 100 / contentLength);
                        HttpLog.getInstance().e(progress + "% ");
                        dialog.setProgress(progress);
                        if (done) {
                            results="下载完成";
                            dialog.setMessage("下载完成");
                        }
                    }

                    @Override
                    public void onStart() {
                        results=Thread.currentThread().getName();
                        HttpLog.getInstance().i("======" + Thread.currentThread().getName());
                        dialog.show();
                    }

                    @Override
                    public void onComplete(String path) {
                        ToastUtils.getInstance(DownloadAbilitySlice.this).showToast("文件保存路径：" + path);
                        dialog.dismiss();
                    }

                    @Override
                    public void onError(final ApiException e) {
                        HttpLog.getInstance().i("======" + Thread.currentThread().getName());
                        ToastUtils.getInstance(DownloadAbilitySlice.this).showToast(e.getMessage());
                        dialog.dismiss();
                    }
                });
    }


    public void onDownloadFile2() {

        StringBuffer sb= new StringBuffer(SCHEMA).append(XIAOMI).append(XPATH).append(XPATH1);
        EasyHttp.downLoad(sb.toString())
                .savePath(FileUtils.getDistDir(this) + "test/QQ")
                .saveName(FileUtils.getFileName(sb.toString()))
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void update(long bytesRead, long contentLength, boolean done) {
                        int progress = (int) (bytesRead * 100 / contentLength);
                        HttpLog.getInstance().e(progress + "% ");
                        dialog.setProgress(progress);
                        if (done) {
                            dialog.setMessage("下载完成");
                            dialog.dismiss();
                        }
                    }
//                    view ohos.agp.components.DirectionalLayout@faf84ac being added, but it already has a parent
                    @Override
                    public void onStart() {
                        if(!dialog.isShowing()){
                            dialog.show();

                        }

                    }

                    @Override
                    public void onComplete(String path) {
                        ToastUtils.getInstance(DownloadAbilitySlice.this).showToast("文件保存路径：" + path);
                        dialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.getInstance(DownloadAbilitySlice.this).showToast(e.getMessage());
                        dialog.dismiss();
                    }
                });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
